package com.sunshine.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by WeiHong on 2016/12/2.
 */
public class GetSqlSessionFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetSqlSession.class);

    private GetSqlSessionFactory(){
    }

    public static SqlSessionFactory sqlSessionFactory;

    synchronized public static SqlSessionFactory getSqlSessionFactory(){
        if (sqlSessionFactory == null){
            InputStream isJDBC = GetSqlSession.class.getResourceAsStream("/jdbc.properties");
            Properties prop = new Properties();
            try {
                prop.load(isJDBC);
            } catch (IOException e) {
                LOGGER.error("prop load error", e);
            }
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            } catch (IOException e) {
                e.printStackTrace();
            }
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, prop);
        }
        return sqlSessionFactory;
    }

}
